using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System.Threading;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class CFSMViewResLoaderCreater : ICFSMResLoaderCreater
    {
        public ICFSMResLoader CreateLoader()
        {
            CFSMViewResLoader loader = ClassPool.Get<CFSMViewResLoader>();
            return loader;
        }

        public void ReleaseLoader(ICFSMResLoader loader)
        {
            ClassPool.PutAutoType(loader as IReusableClass);
        }
    }

    public class CFSMViewResLoader : ICFSMResLoader, IReusableClass
    {
        private ResLoader resLoader;

        public uint MaxStore => 50;

        public byte[] Load(string path)
        {
            if (Thread.CurrentThread.ManagedThreadId == ManagerCenter.mainThreadId)
            {
                resLoader ??= ResLoader.Create();
                var textAsset = resLoader.LoadABAsset<TextAsset>(path);
                if (textAsset == null)
                {
                    return null;
                }
                return textAsset.bytes;
            }
            else
            {
                return LoadOnMainThread(path).AsTask().Result;
            }
        }

        /// <summary>
        /// 异步加载，但实际被调用时会强制转成同步
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private async UniTask<byte[]> LoadOnMainThread(string path)
        {
            await UniTask.SwitchToMainThread();
            resLoader ??= ResLoader.Create();
            var textAsset = resLoader.LoadABAsset<TextAsset>(path);
            if (textAsset == null)
            {
                return null;
            }
            return textAsset.bytes;
        }

        public void OnReset()
        {
            var rl = resLoader;
            resLoader = null;
            rl?.Put2Pool();
        }
    }
}
